package fule.com.kotlindemo.base


import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import butterknife.ButterKnife
import butterknife.Unbinder
import fule.com.kotlindemo.R
import fule.com.kotlindemo.permission.PermissionsChecker

/**
 * @author ch
 */
@Suppress("DEPRECATION")
abstract class BaseFragment<P : BasePresenter<*>>: Fragment() ,BaseView{

    internal var context: Context? = null
    private var dialog: ProgressDialog? = null

    // 控件是否初始化完成
    protected var isViewCreated: Boolean = false

    // 当前fragment是否加载过数据,如加载过数据，则不再加载
    protected var isLoadCompleted: Boolean = false
    //是不是可见
    protected var isUIVisible: Boolean = false

    protected var unbinder: Unbinder? = null

    protected var presenter: P? = null
    private var permissionsChecker: PermissionsChecker? = null

    /**
     * 加载布局
     */
    @LayoutRes
    abstract fun getLayoutId():Int


    // 懒加载,强制子类重写
    protected abstract fun loadData()

    protected abstract fun initView()

    protected abstract fun addListener()

    protected abstract fun createPresenter(): P


    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        isUIVisible = isVisibleToUser
        if (isVisibleToUser && isViewCreated && isUIVisible && !isLoadCompleted) {
            isLoadCompleted = true
            loadData()
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        if (isViewCreated && isUIVisible) {

            loadData()
            isLoadCompleted = true
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val rootView = inflater.inflate(getLayoutId(), container, false)
        unbinder = ButterKnife.bind(this, rootView)
        presenter = createPresenter()
        initView()

        addListener()
        isViewCreated = true
        return rootView
    }


    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        isUIVisible = !hidden
        isLoadCompleted = !hidden
    }

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        this.context = context
    }

    override fun onResume() {
        super.onResume()

    }

    override fun onPause() {
        super.onPause()
    }

    override fun onDestroyView() {
        super.onDestroyView()

        if (presenter != null) {
            presenter!!.detachView()
        }
        if (unbinder != null) {
            unbinder!!.unbind()
        }
    }

    /**
     * 打开指定的activity
     *
     * @param cls
     */
    fun startA(cls: Class<*>) {
        val intent = Intent(context, cls)
        startActivity(intent)
    }

    fun setStatusBar(view: View?) {
        if (view == null) {
            return
        }

    }


    /**
     * toast
     *
     * @param msg
     */
    fun showtoast(msg: String) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
    }

    /**
     * 显示加载动画
     */
    fun showLoadingDialog() {
        if (dialog != null && dialog!!.isShowing) {
            return
        }
        if (null == dialog) {
            dialog = ProgressDialog(context, R.style.AlertDialogStyle)
        }
        dialog!!.setCancelable(false)
        dialog!!.show()

    }

    /**
     * 隐藏加载动画
     */
    fun closeLoadingDialog() {
        if (dialog != null && dialog!!.isShowing) {
            dialog!!.dismiss()
        }
    }

    /**
     * 通过资源res获得view
     *
     * @param res
     * @return
     */
    fun getViewByRes(@LayoutRes res: Int): View {
        return LayoutInflater.from(context).inflate(res, null)
    }


    /**
     * 获得TextView 的文本
     *
     * @param tv
     * @return
     */
    fun getTV(tv: TextView?): String {
        return tv?.text?.toString()?.trim { it <= ' ' } ?: ""
    }


    /**
     * 取值
     *
     * @param key
     * @return
     */
    fun getValueByKey(key: String): String {
        val preferences = context!!.getSharedPreferences(AppConstant.LEDAYOUXUAN, Context.MODE_PRIVATE)
        return preferences.getString(key, "")
    }

    /**
     * 存值
     *
     * @param key
     * @param value
     */
    fun putValueByKey(key: String, value: String) {
        val preferences = context!!.getSharedPreferences(AppConstant.LEDAYOUXUAN, Context.MODE_PRIVATE)
        preferences.edit().putString(key, value).commit()
    }

    private fun showFileDialog() {}

    private fun hideFileDialog() {}

    override fun showLoading() {
        showLoadingDialog()
    }

    override fun hideLoading() {
        closeLoadingDialog()
    }

    override fun showError(msg: String) {
        showtoast(msg)
    }

    override fun onErrorCode(model: Model) {
        if (model != null) {
            if (model.code == 103 || model.code == 400) {
                showtoast(model.commen!!)
            } else if (model.code == 101) {
                //登录失效/未登录
                showtoast(model.commen!!)
                //清除保存的用户信息
                if (activity != null) {

                }
            }
        }
    }

    override fun showLoadingFileDialog() {
        showFileDialog()
    }

    override fun hideLoadingFileDialog() {
        hideFileDialog()
    }

    override fun onProgress(totalSize: Long, downSize: Long) {}

}
